document.addEventListener('DOMContentLoaded', function() {
  // Check if user is authenticated
  if (ApiService.redirectIfNotAuthenticated()) {
    return;
  }
  
  // Initialize components
  const topNavBar = new TopNavBar();
  topNavBar.init();
  
  const sideBar = new SideBar();
  sideBar.init('financial');
  
  // Get product ID from URL parameter
  const urlParams = new URLSearchParams(window.location.search);
  const productId = urlParams.get('id');
  
  if (!productId) {
    showError('产品ID不能为空');
    return;
  }
  
  // Variables
  let productDetail = null;
  let selectedAmount = 0;
  
  // Load product details
  loadProductDetail(productId);
  
  /**
   * Load product detail
   */
  function loadProductDetail(id) {
    ApiService.get(`/api/finance/product/${id}`)
      .then(response => {
        if (response.code === 0 && response.data) {
          productDetail = response.data;
          renderProductDetail(productDetail);
        } else {
          showError(response.message || '获取产品详情失败');
        }
      })
      .catch(error => {
        console.error('Error loading product detail:', error);
        showError('获取产品详情失败');
      });
  }
  
  /**
   * Render product detail
   */
  function renderProductDetail(product) {
    const containerElement = document.getElementById('product-detail-content');
    
    // Parse dates
    const startDate = new Date(product.startTime);
    const endDate = new Date(product.endTime);
    const valueDate = new Date(product.valueDate);
    const dueDate = new Date(product.dueDate);
    
    // Get status information
    const statusClass = getStatusClass(product.status);
    const statusText = getStatusText(product.status);
    
    // Calculate expected profit for minimum amount
    const expectedProfit = (product.minAmount * product.expectedReturn * product.duration) / (100 * 365);
    
    // Prepare quick amount options
    const quickAmounts = [
      product.minAmount,
      product.minAmount * 5,
      product.minAmount * 10,
      product.minAmount * 50,
      product.minAmount * 100
    ].filter(amount => product.maxAmount ? amount <= product.maxAmount : true);
    
    // Build HTML
    let html = `
      <div class="product-overview">
        <div class="product-info">
          <div class="product-name">
            ${product.productName}
            <span class="status-badge ${statusClass}">${statusText}</span>
          </div>
          <div class="product-code">${product.productCode}</div>
          
          <div class="product-highlights">
            <div class="product-highlight">
              <div class="highlight-label">预期年化收益率</div>
              <div class="highlight-value accent">${product.expectedReturn}%</div>
            </div>
            <div class="product-highlight">
              <div class="highlight-label">投资期限</div>
              <div class="highlight-value">${product.duration}天</div>
            </div>
            <div class="product-highlight">
              <div class="highlight-label">起投金额</div>
              <div class="highlight-value">¥${product.minAmount.toFixed(2)}</div>
            </div>
          </div>
          
          <div class="product-meta">
            <div class="product-meta-item">
              <i class="far fa-calendar-alt"></i>
              <span>起息日: ${Utils.formatDate(valueDate)}</span>
            </div>
            <div class="product-meta-item">
              <i class="far fa-calendar-check"></i>
              <span>到期日: ${Utils.formatDate(dueDate)}</span>
            </div>
            <div class="product-meta-item">
              <i class="far fa-clock"></i>
              <span>销售期: ${Utils.formatDate(startDate)} 至 ${Utils.formatDate(endDate)}</span>
            </div>
          </div>
          
          <div class="product-risk risk-level-${product.riskLevel}">
            风险等级: <span class="${getRiskClass(product.riskLevel)}">${getRiskText(product.riskLevel)}</span>
          </div>
          
          <div class="product-sales">
            <div class="sales-progress">
              <div class="sales-progress-bar" style="width: ${product.soldPercentage}%"></div>
            </div>
            <div class="sales-info">
              <div>已售 ${product.soldPercentage}%</div>
              <div>总额 ¥${Utils.formatNumber(product.totalAmount)}</div>
            </div>
          </div>
        </div>
        
        <div class="product-sidebar">
          <div class="card purchase-card">
            <div class="card-header">
              <h3 class="card-title">购买</h3>
            </div>
            <div class="card-body">
              <div class="purchase-amount">
                <div class="amount-input-group">
                  <div class="amount-input-label">¥</div>
                  <input type="number" class="amount-input" id="amount-input" placeholder="请输入购买金额" min="${product.minAmount}" ${product.maxAmount ? `max="${product.maxAmount}"` : ''} step="1">
                </div>
                <div class="purchase-hint">
                  <div>起投金额 ¥${product.minAmount.toFixed(2)}</div>
                  ${product.maxAmount ? `<div>最高金额 ¥${Utils.formatNumber(product.maxAmount)}</div>` : ''}
                </div>
                <div class="quick-amount-options">
                  ${quickAmounts.map(amount => `
                    <div class="quick-amount-option" data-amount="${amount}">¥${Utils.formatNumber(amount)}</div>
                  `).join('')}
                </div>
              </div>
              
              <div class="purchase-summary">
                <div class="summary-item">
                  <div class="summary-label">预期收益</div>
                  <div class="summary-value" id="expected-profit">¥${expectedProfit.toFixed(2)}</div>
                </div>
                <div class="summary-item">
                  <div class="summary-label">收益率</div>
                  <div class="summary-value">${product.expectedReturn}%</div>
                </div>
                <div class="summary-item">
                  <div class="summary-label">投资期限</div>
                  <div class="summary-value">${product.duration}天</div>
                </div>
                <div class="summary-item">
                  <div class="summary-label">到期时间</div>
                  <div class="summary-value">${Utils.formatDate(dueDate)}</div>
                </div>
                <div class="summary-divider"></div>
                <div class="summary-item">
                  <div class="summary-label">到期总额</div>
                  <div class="summary-total" id="total-amount">¥${(product.minAmount + expectedProfit).toFixed(2)}</div>
                </div>
              </div>
              
              <button class="btn btn-primary btn-block" id="purchase-btn" ${product.status !== 1 ? 'disabled' : ''}>
                ${product.status === 1 ? '立即购买' : getStatusText(product.status)}
              </button>
            </div>
          </div>
        </div>
      </div>
      
      <div class="product-tabs">
        <ul class="tab-nav">
          <li class="tab-item active" data-tab="product-info">产品信息</li>
          <li class="tab-item" data-tab="product-desc">产品详情</li>
          <li class="tab-item" data-tab="purchase-notice">购买须知</li>
        </ul>
        
        <div class="tab-content">
          <div class="tab-pane active" id="product-info-tab">
            <div class="feature-list">
              <div class="feature-item">
                <div class="feature-icon">
                  <i class="fas fa-shield-alt"></i>
                </div>
                <div class="feature-content">
                  <div class="feature-title">安全保障</div>
                  <div class="feature-desc">产品经过严格风控筛选，确保资金安全</div>
                </div>
              </div>
              
              <div class="feature-item">
                <div class="feature-icon">
                  <i class="fas fa-chart-line"></i>
                </div>
                <div class="feature-content">
                  <div class="feature-title">收益稳健</div>
                  <div class="feature-desc">预期年化收益${product.expectedReturn}%，定期付息</div>
                </div>
              </div>
              
              <div class="feature-item">
                <div class="feature-icon">
                  <i class="fas fa-calendar-alt"></i>
                </div>
                <div class="feature-content">
                  <div class="feature-title">灵活期限</div>
                  <div class="feature-desc">${product.duration}天投资期限，到期自动返还本金和收益</div>
                </div>
              </div>
              
              <div class="feature-item">
                <div class="feature-icon">
                  <i class="fas fa-hand-holding-usd"></i>
                </div>
                <div class="feature-content">
                  <div class="feature-title">低门槛</div>
                  <div class="feature-desc">起投金额低至¥${product.minAmount.toFixed(2)}，适合各类投资者</div>
                </div>
              </div>
            </div>
            
            <div class="product-section-title">收益计算</div>
            <div class="table-container">
              <table class="data-table">
                <thead>
                  <tr>
                    <th>投资金额</th>
                    <th>投资期限</th>
                    <th>预期年化收益率</th>
                    <th>预期收益</th>
                    <th>到期总额</th>
                  </tr>
                </thead>
                <tbody>
                  ${quickAmounts.map(amount => {
                    const profit = (amount * product.expectedReturn * product.duration) / (100 * 365);
                    const total = amount + profit;
                    return `
                      <tr>
                        <td>¥${Utils.formatNumber(amount)}</td>
                        <td>${product.duration}天</td>
                        <td>${product.expectedReturn}%</td>
                        <td>¥${profit.toFixed(2)}</td>
                        <td>¥${total.toFixed(2)}</td>
                      </tr>
                    `;
                  }).join('')}
                </tbody>
              </table>
            </div>
            
            <div class="product-section-title">收益计算公式</div>
            <div class="formula-container">
              <p>预期收益 = 投资金额 × 预期年化收益率 × 投资天数 ÷ 365</p>
              <p>到期总额 = 投资金额 + 预期收益</p>
            </div>
          </div>
          
          <div class="tab-pane" id="product-desc-tab">
            <div class="product-description">
              ${product.productDesc || `
                <p>本产品是一款${getRiskText(product.riskLevel)}型理财产品，期限为${product.duration}天，预期年化收益率为${product.expectedReturn}%。</p>
                <p>产品特点：</p>
                <ul>
                  <li>期限灵活：${product.duration}天的投资期限，到期自动返还本金和收益</li>
                  <li>收益稳健：预期年化收益率${product.expectedReturn}%</li>
                  <li>投资门槛低：起投金额仅¥${product.minAmount.toFixed(2)}</li>
                  <li>安全性高：经过严格风控筛选的优质资产</li>
                </ul>
                <p>产品资金投向：</p>
                <p>本产品将投资于银行存款、债券、货币市场工具等高流动性资产，稳健安全。</p>
              `}
            </div>
          </div>
          
          <div class="tab-pane" id="purchase-notice-tab">
            <div class="notice-section">
              <div class="notice-item">
                <div class="notice-title">
                  <i class="fas fa-exclamation-circle"></i>
                  风险提示
                </div>
                <div class="notice-content">
                  <p>本产品为${getRiskText(product.riskLevel)}风险等级产品，适合${getRiskSuitableInvestors(product.riskLevel)}。</p>
                  <p>理财非存款，产品有风险，投资需谨慎。过往业绩不代表未来表现，投资者应充分认识投资风险，谨慎投资。</p>
                </div>
              </div>
              
              <div class="notice-item">
                <div class="notice-title">
                  <i class="fas fa-exclamation-circle"></i>
                  购买须知
                </div>
                <div class="notice-content">
                  <p>1. 起购金额：¥${product.minAmount.toFixed(2)}</p>
                  ${product.maxAmount ? `<p>2. 最高购买金额：¥${Utils.formatNumber(product.maxAmount)}</p>` : ''}
                  <p>${product.maxAmount ? '3' : '2'}. 募集期：${Utils.formatDate(startDate)} 至 ${Utils.formatDate(endDate)}</p>
                  <p>${product.maxAmount ? '4' : '3'}. 起息日：${Utils.formatDate(valueDate)}</p>
                  <p>${product.maxAmount ? '5' : '4'}. 到期日：${Utils.formatDate(dueDate)}</p>
                  <p>${product.maxAmount ? '6' : '5'}. 收益计算方式：预期收益 = 投资金额 × 预期年化收益率 × 投资天数 ÷ 365</p>
                </div>
              </div>
              
              <div class="notice-item">
                <div class="notice-title">
                  <i class="fas fa-exclamation-circle"></i>
                  到期处理
                </div>
                <div class="notice-content">
                  <p>产品到期后，本金和收益将自动返还至您的账户，无需手动操作。</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    `;
    
    containerElement.innerHTML = html;
    
    // Initialize tabs
    initTabs();
    
    // Initialize purchase form
    initPurchaseForm(product);
  }
  
  /**
   * Initialize tabs
   */
  function initTabs() {
    const tabItems = document.querySelectorAll('.tab-item');
    
    tabItems.forEach(tab => {
      tab.addEventListener('click', function() {
        const tabId = this.getAttribute('data-tab');
        
        // Update active tab
        tabItems.forEach(t => t.classList.remove('active'));
        this.classList.add('active');
        
        // Update active pane
        const tabPanes = document.querySelectorAll('.tab-pane');
        tabPanes.forEach(pane => pane.classList.remove('active'));
        document.getElementById(`${tabId}-tab`).classList.add('active');
      });
    });
  }
  
  /**
   * Initialize purchase form
   */
  function initPurchaseForm(product) {
    const amountInput = document.getElementById('amount-input');
    const expectedProfitElement = document.getElementById('expected-profit');
    const totalAmountElement = document.getElementById('total-amount');
    const purchaseButton = document.getElementById('purchase-btn');
    
    // Default to minimum amount
    selectedAmount = product.minAmount;
    amountInput.value = selectedAmount;
    
    // Calculate and update profit
    function updateProfit() {
      const amount = parseFloat(amountInput.value) || 0;
      const profit = (amount * product.expectedReturn * product.duration) / (100 * 365);
      const total = amount + profit;
      
      expectedProfitElement.textContent = `¥${profit.toFixed(2)}`;
      totalAmountElement.textContent = `¥${total.toFixed(2)}`;
      
      return { amount, profit, total };
    }
    
    // Handle amount input change
    amountInput.addEventListener('input', function() {
      // Remove selected class from quick options
      document.querySelectorAll('.quick-amount-option').forEach(opt => opt.classList.remove('selected'));
      
      // Update profit calculation
      const { amount } = updateProfit();
      selectedAmount = amount;
    });
    
    // Handle quick amount options
    const quickAmountOptions = document.querySelectorAll('.quick-amount-option');
    quickAmountOptions.forEach(option => {
      option.addEventListener('click', function() {
        const amount = parseFloat(this.getAttribute('data-amount'));
        
        // Update input
        amountInput.value = amount;
        
        // Update selected class
        quickAmountOptions.forEach(opt => opt.classList.remove('selected'));
        this.classList.add('selected');
        
        // Update profit calculation
        updateProfit();
        selectedAmount = amount;
      });
    });
    
    // Handle purchase button
    purchaseButton.addEventListener('click', function() {
      if (product.status !== 1) {
        Toast.info('该产品当前不可购买');
        return;
      }
      
      // Validate amount
      if (!selectedAmount || selectedAmount < product.minAmount) {
        Toast.error(`购买金额不能低于¥${product.minAmount}`);
        return;
      }
      
      if (product.maxAmount && selectedAmount > product.maxAmount) {
        Toast.error(`购买金额不能高于¥${Utils.formatNumber(product.maxAmount)}`);
        return;
      }
      
      // Redirect to purchase page
      window.location.href = `/product-purchase.html?id=${product.id}&amount=${selectedAmount}`;
    });
  }
  
  /**
   * Show error message
   */
  function showError(message) {
    const containerElement = document.getElementById('product-detail-content');
    
    containerElement.innerHTML = `
      <div class="error-state">
        <i class="fas fa-exclamation-circle"></i>
        <p>${message}</p>
        <button class="btn btn-outline" onclick="window.history.back()">
          <i class="fas fa-arrow-left"></i> 返回
        </button>
      </div>
    `;
  }
  
  /**
   * Get risk class for styling
   */
  function getRiskClass(riskLevel) {
    switch (riskLevel) {
      case 1: return 'low';
      case 2: return 'medium';
      case 3: return 'high';
      default: return '';
    }
  }
  
  /**
   * Get risk text
   */
  function getRiskText(riskLevel) {
    switch (riskLevel) {
      case 1: return '低风险';
      case 2: return '中风险';
      case 3: return '高风险';
      default: return '未知风险';
    }
  }
  
  /**
   * Get suitable investors text
   */
  function getRiskSuitableInvestors(riskLevel) {
    switch (riskLevel) {
      case 1: return '保守型、稳健型、平衡型、成长型、进取型投资者';
      case 2: return '稳健型、平衡型、成长型、进取型投资者';
      case 3: return '成长型、进取型投资者';
      default: return '所有类型投资者';
    }
  }
  
  /**
   * Get status class for styling
   */
  function getStatusClass(status) {
    switch (status) {
      case 1: return 'active';
      case 2: return 'sold-out';
      case 3: return 'ended';
      default: return '';
    }
  }
  
  /**
   * Get status text
   */
  function getStatusText(status) {
    switch (status) {
      case 0: return '未上架';
      case 1: return '发售中';
      case 2: return '已售罄';
      case 3: return '已到期';
      default: return '未知状态';
    }
  }
});
